from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from . import score_crud
from .score_schema import Score_schema
from .score_crud import add_score, mod_score, del_score
from .score_database import SessionLocal

app02 = APIRouter()

# 依赖项：获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 录入考核成绩
@app02.post("/score/add/", response_model=Score_schema,summary='添加考核成绩')
def create_score(score: Score_schema, db: Session = Depends(get_db)):
    db_score = add_score(db, score)
    if not db_score:
        raise HTTPException(
            status_code=400, 
            detail=f"学生{score.student_id}的第{score.exam_sequence}次考核成绩已存在"
        )
    return db_score

# 修改考核成绩
@app02.put("/score/update/", response_model=Score_schema,summary='修改考核成绩')
def update_score(score: Score_schema, db: Session = Depends(get_db)):
    db_score = mod_score(db, score)
    if not db_score:
        raise HTTPException(
            status_code=404, 
            detail=f"学生{score.student_id}的第{score.exam_sequence}次考核成绩不存在"
        )
    return db_score

# 删除考核成绩
@app02.delete("/score/{student_id}/{exam_sequence}", summary="删除考核成绩")
def delete_score(student_id: int, exam_sequence: int, db: Session = Depends(get_db)):
    db_score = del_score(db, student_id, exam_sequence)
    if not db_score:
        raise HTTPException(
            status_code=404,
            detail=f"学生{student_id}的第{exam_sequence}次考核成绩不存在"
        )
    return {"message": "成绩删除成功"}

@app02.get("/score/above80/", summary="查询每次考试成绩均80分以上的学生")
async def query_all_above_80(db: Session = Depends(get_db)):
    return score_crud.get_stu_all_above_80(db)

@app02.get("/score/fail_more_than_two/", summary="查询有2次以上不及格的学生")
async def query_fail_more_than_two(db: Session = Depends(get_db)):
    return score_crud.get_stu_more_than_two_fail(db)

@app02.get("/score/class_avg/", summary="统计每次考试每个班级的平均分")
async def query_class_avg_per_exam(db: Session = Depends(get_db)):
    return score_crud.get_class_avg_per_exam(db)